package catalogue

import (
	"clouds.lgb24kcs.cn/controllers/catalogue/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/history"
	"clouds.lgb24kcs.cn/utils/oss"
	"errors"
	"github.com/gin-gonic/gin"
)

type DeleteObjectAPI struct {
}

var DeleteObject DeleteObjectAPI

func (a *DeleteObjectAPI) DeleteCatalogue(c *gin.Context, req request.DelCatalogues, userId int64) {
	//查询数据oss存储对象信息获取秘钥
	BucketInfo := models.Storage{}
	api := oss.OSS{}

	tx := global.APP.DB.Where("id=? and userid=?", req.BucketID, userId).First(&BucketInfo)
	if tx.Error != nil || tx.RowsAffected == 0 {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.CataloguetDel, "删除失败")
	} else {
		client := api.NewClient(BucketInfo.Accesskey, BucketInfo.Secretkey, BucketInfo.Zone)
		tmp := []string{}
		for _, item := range req.CatalogueName {
			tmp = append(tmp, item.CatalogueName)
		}
		if err := api.CatalogueDelete(client, req.BucketName, tmp); err != nil {
			utils.Fail(c, errorx.CataloguetDel, err.Error())
		} else {
			for _, item := range req.CatalogueName {
				catalogueInfo := models.Catalogue{}
				first := global.APP.DB.Where("id=? and bucketid=? and userid=?", item.CatalogueID, req.BucketID, userId).Delete(&catalogueInfo)
				if first.Error != nil {
					utils.Fail(c, errorx.CataloguetDel, first.Error.Error())
				} else if first.RowsAffected == 0 {
					global.APP.Log.Error(errors.New("数据库没有该条数据").Error())
					utils.Fail(c, errorx.CataloguetDel, first.Error.Error())
				} else {
					/*因为这里是连级删除，目录下所有的文件也会被删除，所以这是操作数据库删除files表中的对应数据*/
					tx := global.APP.DB.Where("bucketname=? and root_dir=? and  user_id=?", req.BucketName, item.CatalogueName, userId).Delete(&models.Files{})
					if tx.Error != nil {
						global.APP.Log.Error(tx.Error.Error())
						utils.Fail(c, errorx.ObjectDel, tx.Error.Error())
					} else {
						if err := history.HistoryCreate(userId, c.Request.Method, c.Request.URL.String(), c.Request.Host); err != nil {
							utils.Fail(c, errorx.ObjectSearch, err.Error())
						} else {
							utils.Success(c, 0, "删除成功")
						}

					}
				}
			}
		}

	}

}
